//@ts-nocheck
/** 我们为了区分state，有两种思路*/
//1) 将_state做成一个对象
// _state = {n:0,m:0}
// 那么调用useState时就需要类似于这样设置
// useState(key,value)
// 但useState不是这样设计的

//2) 把_state做成数组
// 比如_state = [0,0]

import React from 'react';
import ReactDOM from 'react-dom';
const rootElement = document.getElementById('root');

const _state = [];
let index = 0;

const render = () => {
  index = 0; /** ←每次重新渲染后index变为0*/
  ReactDOM.render(<App/>, rootElement)
};

const myUseState = initialValue => {
  const currentIndex = index;
  _state[currentIndex] = _state[currentIndex] === undefined ? initialValue : _state[currentIndex];
  const setState = newValue => {
    _state[currentIndex] = newValue;
    render()
  };
  index += 1;
  return [_state[currentIndex], setState];
};

function App(){
  const [n, setN] = myUseState(0);
  const [m, setM] = myUseState(0);

  // setTimeout(() => {
  //   console.log(n); // 每次渲染都是一个独立的闭包,打印的是当前闭包了的n,即使我们已经将"n"(实际上改的不是n,而是一个中间变量x)改成了其它值
  // }, 3000);

  return (
    <div className="App">
      <p>{n}</p>
      <p>
        <button onClick={() => setN(n + 1)}>+1</button>
      </p>
      <p>{m}</p>
      <p>
        <button onClick={() => setM(m + 1)}>+1</button>
      </p>
    </div>
  );
}

ReactDOM.render(<App/>, rootElement);
